package by.wind.drebedengi.datalayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import java.util.Map.Entry;

import by.wind.drebedengi.datalayer.bean.Source;

public class GetSourceList extends AbstractAction {

	public static final String SOAP_ACTION = "getSourceList";
	public static final String METHOD_NAME = "getSourceList";
	
	private ArrayList<Source> itsSourceList = new ArrayList<Source>();
	
	@Override
	public void loadData() throws Exception {
		HashMap<String, Object> propertyList = new HashMap<String, Object>();
		propertyList.put(Constants.API_ID_KEY, Constants.API_ID_VALUE);
		propertyList.put(Constants.LOGIN_KEY, Constants.LOGIN_VALUE);
		propertyList.put(Constants.PASS_KEY, Constants.PASS_VALUE);
		
		Vector<Hashtable<String,String>> itsData = (Vector<Hashtable<String,String>>) loadData(METHOD_NAME, SOAP_ACTION, propertyList);
		for(int i = 0 ; i< itsData.size() ; i ++) {
			itsSourceList.add(convertHashtableToSource(itsData.get(i)));
		}
	}
	
	private Source convertHashtableToSource(Hashtable<String, String> element) {
		Source sourceElement = new Source();
		Iterator<Entry<String, String>> iterator = element.entrySet().iterator();
		while(iterator.hasNext()) {
			
			String key = iterator.next().getKey();
			String value = element.get(key);
			if (key.equals(Source.ID)) {
				sourceElement.setServer_id(Long.parseLong(value));
			} else if (key.equals(Source.PARENT_ID)) {
				sourceElement.setParentId(Long.parseLong(value));
			} else if (key.equals(Source.BUDGET_FAMILY_ID)) {
				sourceElement.setBudgetFamilyId(Long.parseLong(value));
			} else if (key.equals(Source.TYPE)) {
				sourceElement.setType(Long.parseLong(value));
			} else if (key.equals(Source.NAME)) {
				sourceElement.setName(value);
			} else if (key.equals(Source.SORT)) {
				sourceElement.setSort(Long.valueOf(value));
			} else if (key.equals(Source.IS_HIDDEN)) {
				if (value.equals("t")) {
					sourceElement.setHidden(true);
				}
			}
			
		}
		
		return sourceElement;
	}

	public ArrayList<Source> getSourceList() {
		return itsSourceList;
	}

}
